﻿Imports System.Data.SqlClient
Imports System.Windows.Forms

Public Class frmMakePayment

    Sub Clear()
        Me.txtAccNoC.Clear()
        Me.txtAccNameC.Clear()
        Me.CombSource.Text = ""
        Me.txtAmount.Clear()
        Me.txtWrittenValue.Clear()
        Me.txtCheqDetails.Clear()
        Me.txtTransferDetails.Clear()
        Me.RCash.Checked = True
        Me.txtDescr.Clear()
        Me.txtReceivedBy.Clear()
        Me.DTPTrans.Value = Date.Today
        Me.CombBranch.SelectedIndex = -1
        Me.GridVoucher.Rows.Clear()
        Me.GridVoucher.Focus()
    End Sub

    Sub FillBranches()
        Try
            Me.Cursor = Cursors.WaitCursor

            Me.CombBranch.Items.Clear()
            Dim Branches As ArrayList = GetBranches()

            For Each Branch As String In Branches
                Me.CombBranch.Items.Add(Branch)
            Next

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            MsgBox(ex.ToString)
        End Try
    End Sub

    Private Sub frmMakePayment_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.WindowState = FormWindowState.Maximized

        FillBeneficiariesList()
        FillBranches()
    End Sub

    Sub FillBeneficiariesList()
        Try
            Me.Cursor = Cursors.WaitCursor

            Dim cmd As New SqlCommand("Select Distinct BeneficiaryName From BeneficiariesList", cnn)
            Dim Reader As SqlDataReader

            Me.CombSource.Items.Clear()

            cnn.Open()
            Reader = cmd.ExecuteReader
            While Reader.Read
                Me.CombSource.Items.Add(Reader.Item(0))
            End While
            cnn.Close()

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
            If cnn.State = ConnectionState.Open Then
                cnn.Close()
            End If
            MsgBox(ex.ToString)
        End Try
    End Sub

    Private Sub btnGSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGSave.Click
        Me.Close()
    End Sub

    Private Sub btnGClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGClose.Click
        Me.ErrProv.Clear()
        If CDbl(Me.txtAmount.Text) = 0 Then
            Me.ErrProv.SetError(Me.txtAmount, "Please enter valid payments amount")
            Me.GridVoucher.Focus()

        ElseIf Me.CombSource.Text.Trim.Length = 0 Then
            Me.ErrProv.SetError(Me.CombSource, "Please fill in all details")
            Me.CombSource.Focus()

        ElseIf Me.RCheq.Checked = True And Me.txtCheqDetails.Text.Trim.Length = 0 Then
            Me.ErrProv.SetError(Me.txtCheqDetails, "Please fill in all details")
            Me.txtCheqDetails.Focus()

        ElseIf Me.RTransfer.Checked = True And Me.txtTransferDetails.Text.Trim.Length = 0 Then
            Me.ErrProv.SetError(Me.txtTransferDetails, "Please fill in all details")
            Me.txtTransferDetails.Focus()

        ElseIf Me.txtAccNameC.Text.Trim.Length = 0 Then
            Me.ErrProv.SetError(Me.txtAccNoC, "Please fill in all details")
            Me.txtAccNoC.Focus()

        ElseIf Me.txtDescr.Text.Trim.Length = 0 Then
            Me.ErrProv.SetError(Me.txtDescr, "Please fill in all details")
            Me.txtDescr.Focus()

        ElseIf Me.txtReceivedBy.Text.Trim.Length = 0 Then
            Me.ErrProv.SetError(Me.txtReceivedBy, "Please fill in all details")
            Me.txtReceivedBy.Focus()

        ElseIf ValidateDate(Me.DTPTrans.Value) = False Then
            Me.ErrProv.SetError(Me.DTPTrans, "Date isn't accepted")

        ElseIf Me.CombBranch.SelectedIndex = -1 Then
            Me.ErrProv.SetError(Me.CombBranch, "Please fill in all details")

        Else
            Try
                Me.Cursor = Cursors.WaitCursor

                'Validate rows
                Dim Valid As Boolean = True
                For Each row As DataGridViewRow In Me.GridVoucher.Rows
                    If row.Index <> (Me.GridVoucher.Rows.Count - 1) Then
                        If row.Cells(4).Style.BackColor = Color.Salmon OrElse row.Cells(6).Style.BackColor = Color.Salmon Then
                            row.ErrorText = "Please fill in all fields"
                            Valid = False
                        Else
                            row.ErrorText = ""
                        End If
                    End If
                Next

                If Valid = False Then
                    Me.Cursor = Cursors.Default
                    Exit Sub
                End If

                Dim MoveNo, SNo As Integer
                Dim PaymentDetails As String
                Dim AccNamesC(5) As String

                If Me.RCash.Checked = True Then
                    PaymentDetails = "Cash"
                ElseIf Me.RCheq.Checked = True Then
                    PaymentDetails = "Chq # " & Me.txtCheqDetails.Text.Trim
                ElseIf Me.RTransfer.Checked = True Then
                    PaymentDetails = Me.txtTransferDetails.Text.Trim
                End If

                Dim cmd As New SqlCommand
                Dim Trans As SqlTransaction

                AccNamesC = GetAccNames(Me.txtAccNoC.Text.Trim)

                cnn.Open()
                Trans = cnn.BeginTransaction
                cmd.Connection = cnn
                cmd.Transaction = Trans

                'Get Doc SNo
                cmd.CommandText = "Select IsNull(Max(PaperNo),0) From TempTransactions Where TransType=N'Pay' and Branch=N'" & Me.CombBranch.Text & "'"
                SNo = CInt(cmd.ExecuteScalar) + 1

                'Get Move No.
                cmd.CommandText = "Select IsNull(Max(MoveNo),0) From TempTransactions Where Branch=N'" & Branch & "' and Year(TransDate)= " & Me.DTPTrans.Value.Year
                MoveNo = CInt(cmd.ExecuteScalar) + 1

                'Debit Side
                For Each row As DataGridViewRow In Me.GridVoucher.Rows
                    If row.Index <> (Me.GridVoucher.Rows.Count - 1) Then
                        cmd.CommandText = "Insert Into TempTransactions (MoveNo,TransType,PaperNo,DestSource,Descr,AccNo," & _
                                          "Acc1,Acc2,Acc3,Acc4,ChNo,Writting,TotalOut,SavedUser,TransDate,Branch,ReceivedBy) " & _
                                          "Values (@MoveNo,@TransType,@PaperNo,@DestSource,@Descr,@AccNo," & _
                                          "@Acc1,@Acc2,@Acc3,@Acc4,@ChNo,@Writting,@TotalOut,@SavedUser,@TransDate,@Branch,@ReceivedBy)"

                        cmd.Parameters.Clear()
                        cmd.Parameters.AddWithValue("@MoveNo", MoveNo)
                        cmd.Parameters.AddWithValue("@TransType", "Pay")
                        cmd.Parameters.AddWithValue("@PaperNo", SNo)
                        cmd.Parameters.AddWithValue("@DestSource", Me.CombSource.Text.Trim)
                        cmd.Parameters.AddWithValue("@Descr", Me.txtDescr.Text.Trim)
                        cmd.Parameters.AddWithValue("@AccNo", row.Cells(0).Value)
                        cmd.Parameters.AddWithValue("@Acc1", row.Cells(1).Value)
                        cmd.Parameters.AddWithValue("@Acc2", row.Cells(2).Value)
                        cmd.Parameters.AddWithValue("@Acc3", row.Cells(3).Value)
                        cmd.Parameters.AddWithValue("@Acc4", row.Cells(4).Value)
                        cmd.Parameters.AddWithValue("@ChNo", PaymentDetails)
                        cmd.Parameters.AddWithValue("@Writting", Me.txtWrittenValue.Text.Trim)
                        cmd.Parameters.AddWithValue("@TotalOut", CDbl(row.Cells(6).Value))
                        cmd.Parameters.AddWithValue("@SavedUser", CurrentUser)
                        cmd.Parameters.AddWithValue("@TransDate", Me.DTPTrans.Value)
                        cmd.Parameters.AddWithValue("@Branch", Me.CombBranch.Text)
                        cmd.Parameters.AddWithValue("@ReceivedBy", Me.txtReceivedBy.Text.Trim)
                        cmd.ExecuteNonQuery()
                    End If
                Next

                'Credit Side
                cmd.CommandText = "Insert Into TempTransactions (MoveNo,TransType,PaperNo,DestSource,Descr,AccNo," & _
                                 "Acc1,Acc2,Acc3,Acc4,ChNo,Writting,TotalIn,SavedUser,TransDate,Branch,ReceivedBy) " & _
                                 "Values (@MoveNo,@TransType,@PaperNo,@DestSource,@Descr,@AccNo," & _
                                 "@Acc1,@Acc2,@Acc3,@Acc4,@ChNo,@Writting,@TotalIn,@SavedUser,@TransDate,@Branch,@ReceivedBy)"

                cmd.Parameters.Clear()
                cmd.Parameters.AddWithValue("@MoveNo", MoveNo)
                cmd.Parameters.AddWithValue("@TransType", "Pay")
                cmd.Parameters.AddWithValue("@PaperNo", SNo)
                cmd.Parameters.AddWithValue("@DestSource", Me.CombSource.Text.Trim)
                cmd.Parameters.AddWithValue("@Descr", Me.txtDescr.Text.Trim)
                cmd.Parameters.AddWithValue("@AccNo", Me.txtAccNoC.Text)
                cmd.Parameters.AddWithValue("@Acc1", AccNamesC(0))
                cmd.Parameters.AddWithValue("@Acc2", AccNamesC(1))
                cmd.Parameters.AddWithValue("@Acc3", AccNamesC(2))
                cmd.Parameters.AddWithValue("@Acc4", AccNamesC(3))
                cmd.Parameters.AddWithValue("@ChNo", PaymentDetails)
                cmd.Parameters.AddWithValue("@Writting", Me.txtWrittenValue.Text.Trim)
                cmd.Parameters.AddWithValue("@TotalIn", CDbl(Me.txtAmount.Text.Trim))
                cmd.Parameters.AddWithValue("@SavedUser", CurrentUser)
                cmd.Parameters.AddWithValue("@TransDate", Me.DTPTrans.Value)
                cmd.Parameters.AddWithValue("@Branch", Me.CombBranch.Text)
                cmd.Parameters.AddWithValue("@ReceivedBy", Me.txtReceivedBy.Text.Trim)
                cmd.ExecuteNonQuery()

                Trans.Commit()
                cnn.Close()

                MsgBox("Saved Successfully")

                'PrintPayBill("Pay", SNo, Branch)
                'PrintVoucher(MoveNo, Me.DTPTrans.Value.Year)

                Clear()

                Me.Cursor = Cursors.Default
            Catch ex As Exception
                Me.Cursor = Cursors.Default
                If cnn.State = ConnectionState.Open Then
                    cnn.Close()
                End If
                MsgBox(ex.ToString)
            End Try
        End If
    End Sub

    Private Sub txtAmount_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtAmount.TextChanged
        Me.ErrProv.Clear()
        Try
            If Me.txtAmount.Text.Trim.Length = 0 Then
                Me.txtWrittenValue.Clear()
            Else
                Me.txtWrittenValue.Text = SpellNumber(CDbl(Me.txtAmount.Text)).ToString

                Me.txtWrittenValue.Text = Me.txtWrittenValue.Text.Replace("Dollar", "Riyal")
                Me.txtWrittenValue.Text = Me.txtWrittenValue.Text.Replace("and No Halala", "")
                Me.txtWrittenValue.Text = Me.txtWrittenValue.Text.Replace("Cent", "Halala")
                Me.txtWrittenValue.Text = Me.txtWrittenValue.Text & " Only"
            End If
        Catch ex As Exception
            Me.txtAmount.Clear()
            Me.txtAmount.Focus()
        End Try
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Clear()
    End Sub

    Sub CheckPaymentSource()
        If Me.RCash.Checked = True Then
            Me.txtCheqDetails.ReadOnly = True
            Me.txtCheqDetails.Clear()
            Me.txtTransferDetails.ReadOnly = True
            Me.txtTransferDetails.Clear()

        ElseIf Me.RCheq.Checked = True Then
            Me.txtCheqDetails.ReadOnly = False
            Me.txtCheqDetails.Clear()
            Me.txtCheqDetails.Focus()
            Me.txtTransferDetails.ReadOnly = True
            Me.txtTransferDetails.Clear()

        ElseIf Me.RTransfer.Checked = True Then
            Me.txtCheqDetails.ReadOnly = True
            Me.txtCheqDetails.Clear()
            Me.txtTransferDetails.ReadOnly = False
            Me.txtTransferDetails.Clear()
            Me.txtTransferDetails.Focus()
        End If
    End Sub

    Private Sub RCash_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RCash.CheckedChanged
        CheckPaymentSource()
    End Sub

    Private Sub RCheq_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RCheq.CheckedChanged
        CheckPaymentSource()
    End Sub

    Private Sub RTransfer_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RTransfer.CheckedChanged
        CheckPaymentSource()
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        Dim a As New frmListBeneficiary
        a.ShowDialog()

        FillBeneficiariesList()
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim a As New frmSelectAccount
        a.ShowDialog()

        If SelAccNo <> "" Then
            Me.txtAccNoC.Text = SelAccNo
            Me.txtAccNameC.Text = SelAccName
        End If
    End Sub

    Private Sub txtAccNoC_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtAccNoC.KeyUp
        If e.KeyCode = Keys.Enter Then
            Me.txtAccNameC.Text = GetAccName(Me.txtAccNoC.Text.Trim)
        End If
    End Sub

    Private Sub txtAccNoC_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtAccNoC.TextChanged
        Me.txtAccNameC.Clear()
    End Sub

    Private Sub GridVoucher_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles GridVoucher.CellClick
        If e.ColumnIndex = 5 Then
            Try
                Dim a As New frmSelectAccount
                a.ShowDialog()

                If SelAccNo <> "" Then
                    Me.Cursor = Cursors.WaitCursor

                    'Get acc path
                    Dim AccNames(3) As String
                    AccNames = GetAccNames(SelAccNo)

                    Me.GridVoucher.CurrentRow.Cells(0).Value = SelAccNo
                    Me.GridVoucher.CurrentRow.Cells(1).Value = AccNames(0)
                    Me.GridVoucher.CurrentRow.Cells(2).Value = AccNames(1)
                    Me.GridVoucher.CurrentRow.Cells(3).Value = AccNames(2)
                    Me.GridVoucher.CurrentRow.Cells(4).Value = AccNames(3)

                    Me.Cursor = Cursors.Default
                End If
            Catch ex As Exception
                Me.Cursor = Cursors.Default
                MsgBox(ex.ToString)
            End Try
        ElseIf e.ColumnIndex = 7 Then
            If e.RowIndex < (Me.GridVoucher.Rows.Count - 1) Then
                Me.GridVoucher.Rows.RemoveAt(e.RowIndex)
            End If
        End If
    End Sub

    Private Sub GridVoucher_RowsRemoved(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowsRemovedEventArgs) Handles GridVoucher.RowsRemoved
        Calculate()
        ValidateGrid()
    End Sub

    Private Sub GridVoucher_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles GridVoucher.CellEndEdit
        If e.ColumnIndex = 0 Then
            Try
                If Me.GridVoucher.CurrentCell.Value <> "" Then
                    Me.Cursor = Cursors.WaitCursor

                    'Get acc path
                    Dim AccNames(3) As String
                    AccNames = GetAccNames(Me.GridVoucher.CurrentCell.Value)

                    Me.GridVoucher.CurrentRow.Cells(1).Value = AccNames(0)
                    Me.GridVoucher.CurrentRow.Cells(2).Value = AccNames(1)
                    Me.GridVoucher.CurrentRow.Cells(3).Value = AccNames(2)
                    Me.GridVoucher.CurrentRow.Cells(4).Value = AccNames(3)

                    Me.Cursor = Cursors.Default
                Else
                    Me.GridVoucher.CurrentRow.Cells(1).Value = ""
                    Me.GridVoucher.CurrentRow.Cells(2).Value = ""
                    Me.GridVoucher.CurrentRow.Cells(3).Value = ""
                    Me.GridVoucher.CurrentRow.Cells(4).Value = ""
                End If
            Catch ex As Exception
                Me.Cursor = Cursors.Default
                MsgBox(ex.ToString)
            End Try
        ElseIf e.ColumnIndex = 6 Then
            Try
                Me.GridVoucher.CurrentCell.Value = CDbl(Me.GridVoucher.CurrentCell.Value).ToString("N2")
            Catch ex As Exception
                Me.GridVoucher.CurrentCell.Value = "0.00"
            End Try
        End If

        Calculate()
        ValidateGrid()
    End Sub

    Sub Calculate()
        Try
            Me.Cursor = Cursors.WaitCursor

            Dim Total As Double

            For Each row As DataGridViewRow In Me.GridVoucher.Rows
                Total += CDbl(row.Cells(6).Value)
            Next

            Me.txtAmount.Text = Total.ToString("N2")

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    Sub ValidateGrid()
        Try
            Me.Cursor = Cursors.WaitCursor

            For Each row As DataGridViewRow In Me.GridVoucher.Rows
                If row.Cells(4).Value = "" Then
                    row.Cells(4).Style.BackColor = Color.Salmon
                Else
                    row.Cells(4).Style.BackColor = row.DefaultCellStyle.BackColor
                End If

                If CDbl(row.Cells(6).Value) = 0 Then
                    row.Cells(6).Style.BackColor = Color.Salmon
                Else
                    row.Cells(6).Style.BackColor = row.DefaultCellStyle.BackColor
                End If
            Next

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub ChAccPath_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChAccPath.CheckedChanged
        If Me.ChAccPath.Checked = True Then
            Me.Acc1.Visible = True
            Me.Acc2.Visible = True
            Me.Acc3.Visible = True
        ElseIf Me.ChAccPath.Checked = False Then
            Me.Acc1.Visible = False
            Me.Acc2.Visible = False
            Me.Acc3.Visible = False
        End If
    End Sub
End Class